<template>
  <div style="width: 760px">
    <cus-modal
      ref="modal"
      :title="form.id == '' ? '添加' : '编辑'"
      @on-visible-change="onVisibleChange"
      width="760"
      @onOk="onOk"
    >
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="110">
        <FormItem
          label="供应商名称"
          prop="name"
          :rules="[
            {
              required: true,
              message: '供应商名称不能为空',
              trigger: 'blur',
            },
            {
              required: true,
              message: '名称只能汉字、数字、字母',
              pattern: '^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$',
              trigger: 'blur',
            },
          ]"
        >
          <Input
            v-model="form.name"
            clearable
            :disabled="form.id ? true : false"
            maxlength="20"
            @on-blur="postApiSupplierIssuppliernameApi()"
            style="width: 200px"
            placeholder="请输入供应商"
          ></Input>
        </FormItem>
        <FormItem
          label="供应商编码"
          prop="supplyCode"
          :rules="[
            {
              required: true,
              message: '供应商编码不能为空',
              trigger: 'blur',
            },
            {
              required: true,
              message: '供应商编码只能字母或数字',
              pattern: '^[0-9a-zA-Z]*$',
              trigger: 'blur',
            },
          ]"
        >
          <Input
            v-model="form.supplyCode"
            clearable
            :disabled="form.id ? true : false"
            maxlength="20"
            style="width: 200px"
            placeholder="请输入供应商编码"
          ></Input>
        </FormItem>
        <FormItem
          label="供应种类"
          prop="materialClassValue"
          :rules="{
            required: true,
            type: 'array',
            message: '供应种类不能为空',
            trigger: 'change',
          }"
        >
          <CheckboxGroup v-model="form.materialClassValue" @on-change="check">
            <Checkbox
              :label="item.id"
              :disabled="item.isSupplyCheck == 1 ? true : false"
              v-for="(item, index) in materialClassTree"
              :key="index"
              >{{ item.categoryName }}</Checkbox
            >
          </CheckboxGroup>
        </FormItem>
        <FormItem
          label="联系人"
          prop="contact"
          :rules="[
            {
              required: true,
              message: '联系人不能为空',
              trigger: 'blur',
            },
            {
              required: true,
              message: '联系人只能汉字、数字、字母',
              pattern: '^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$',
              trigger: 'blur',
            },
          ]"
        >
          <Input
            v-model="form.contact"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入联系人"
          ></Input>
        </FormItem>
        <FormItem
          label="电话号码"
          prop="mobile"
          :rules="[
            {
              required: 'true',
              message: '电话号码不能为空',
              trigger: 'blur',
            },
          ]"
        >
          <Input
            v-model="form.mobile"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入电话号码"
          ></Input>
        </FormItem>
        <FormItem
          label="地址"
          prop="address"
          :rules="{ required: true, message: '地址不能为空', trigger: 'blur' }"
        >
          <Input
            v-model="form.address"
            clearable
            maxlength="150"
            style="width: 200px"
            placeholder="请输入地址"
          ></Input>
        </FormItem>
        <FormItem label="邮箱地址" prop="email" class="redDot">
          <Input
            v-model="form.email"
            clearable
            maxlength="20"
            style="width: 200px"
            placeholder="请输入邮箱地址"
          ></Input>
        </FormItem>
        <FormItem label="资质有效期">
          <DatePicker
            type="daterange"
            show-week-numbers
            transfer
            ref="formDate"
            :value="dateTime"
            @on-change="datePickerChange"
            placement="bottom-end"
            placeholder="开始日期 - 结束日期"
            style="width: 200px"
          />
        </FormItem>
        <FormItem label="资质文件">
          <div style="width: 200px; display: flex">
            <Upload
              ref="upload"
              :show-upload-list="false"
              v-if="uploadList.length < 3"
              :format="['jpg', 'jpeg', 'png']"
              :max-size="1024"
              accept="image/jpeg,image/jpg,image/png"
              :before-upload="handleBeforeUpload"
              multiple
              type="drag"
              action=""
              style="display: inline-block; width: 58px; margin-right: 13px"
            >
              <div style="width: 58px; height: 58px; line-height: 58px">
                <Icon type="ios-camera" size="20"></Icon>
              </div>
            </Upload>
            <div class="imgContent" v-if="uploadList.length > 0">
              <!-- 准备上传的图片列表 -->
              <div
                class="imgContent-item"
                v-for="(item, index) in uploadList"
                :key="index"
                :style="{ marginLeft: index == 0 ? '0' : '13px' }"
              >
                <img
                  :src="item"
                  alt=""
                  style="width: 58px; height: 58px; line-height: 58px"
                />
                <div class="imgContent-item-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item)"></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click="handleRemove(item, index)"
                  ></Icon>
                </div>
              </div>
            </div>
          </div>
        </FormItem>
      </Form>
      <Spin size="large" fix v-if="loading"></Spin>
      <!--预览图片-->
      <imgPreview ref="imgPreview"></imgPreview>
    </cus-modal>
  </div>
</template>

<script>
import {
  postApiSupplierIssuppliername,
  postApiPurchasingSupplierSave,
  postApiPurchasingSupplierUpdate,
  getProductCategoryList,
  deleteApiCertificationPicture,
} from "@/api/organ/dishesModule.js";
import imgPreview from "./imgPreview.vue";

const form = {
  id: "",
  name: "", //供应商名称
  materialClassValue: [], // 供应商种类
  supplyCode: "", // 供应商编码
  contact: "", // 联系人
  mobile: "", // 电话号码
  address: "", // 地址
  email: "", // Email邮箱
  startTime: "", // 资质有效期开始时间
  stopTime: "", // 资质有效期结束时间
  uploadFiles: [], //上传资质文件
};

export default {
  name: "addDistinctionModal",
  components: { imgPreview },
  data() {
    return {
      loading: false,
      ruleValidate: {
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // 如果邮箱存在
              if (value) {
                if (this.$cu.test.email(value)) {
                  callback();
                } else {
                  return callback(new Error("邮箱格式错误"));
                }
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      form: form,
      materialClassTree: [], //食材种类数据
      uploadList: [], //图片列表集合
      imgPreviewUrl: "", //图片地址
      dateTime: [], //资质时间
      deleteImgList: [],
    };
  },
  mounted() {
    this.form = this.$cu.deepClone(form);
  },
  methods: {
    onVisibleChange(v) {
      this.$refs["formValidate"].resetFields();
      this.$refs.formDate.handleClear(); //清空时间
      if (!v) this.form = this.$cu.deepClone(form);
    },
    check() {
      console.log(this.form.materialClassValue);
    },
    show() {
      this.$refs["modal"].show = true;
      this.getProductCategoryListApi();
    },
    datePickerChange(date) {
      this.form.startTime = date[0];
      this.form.stopTime = date[1];
    },
    onOk() {
      this.$refs["formValidate"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.id) {
            if (this.deleteImgList != "") {
              let list = []
              this.deleteImgList.forEach(item => {
                list.push(item.fun(item.file))
              })
              Promise.all(list).then(() => {
                this.postApiPurchasingSupplierUpdateApi();
              });
            } else {
              this.postApiPurchasingSupplierUpdateApi();
            }
          } else {
            this.postApiPurchasingSupplierSaveApi();
          }
        }
      });
    },
    handleBeforeUpload(file) {
      if (this.uploadList.length <= 2) {
        const _this = this;
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          // 文件base64
          const fileBase64 = this.result;
          _this.uploadList.push(fileBase64);
          _this.form.uploadFiles.push(file);
        };
      } else {
        this.$Message.info("最多可添加三张文件！");
      }
      console.log(this.form.uploadFiles);
      return;
    },
    handleView(v) {
      this.$refs["imgPreview"].show(v);
      this.$refs["imgPreview"].imgPreviewUrl = v;
    },
    handleRemove(file, index) {
      this.uploadList.splice(index, 1);
      this.form.uploadFiles.splice(index, 1);
      // 当删除的部位base64时为后台传来的链接时，添加到删除图片列表中
      if (file.indexOf("data:") == -1 && file.indexOf("base64") == -1) {
        // this.deleteImgList.push(this.deleteApiCertificationPictureApi(file))
        this.deleteImgList.push({'fun': this.deleteApiCertificationPictureApi,'file': file});
      }

      console.log(this.form.uploadFiles);
    },
    //添加供应商信息前效验----------------接口
    postApiSupplierIssuppliernameApi() {
      return new Promise((resolve) => {
        postApiSupplierIssuppliername({
          supplierName: this.form.name,
        }).then((res) => {
          if (res.code === 1) {
            resolve();
          }
        });
      });
    },
    //添加供应商信息---------------------接口
    postApiPurchasingSupplierSaveApi() {
      console.log(this.form.uploadFiles);
      return new Promise((resolve) => {
        let params = new FormData();
        params.append("name", this.form.name);
        params.append("supplyCode", this.form.supplyCode);
        params.append("contact", this.form.contact);
        params.append("mobile", this.form.mobile);
        params.append("address", this.form.address);
        params.append("email", this.form.email);
        params.append("startTime", this.form.startTime);
        params.append("stopTime", this.form.stopTime);
        params.append("materialClassValue", this.form.materialClassValue);
        params.append("file1", this.form.uploadFiles[0]);
        params.append("file2", this.form.uploadFiles[1]);
        params.append("file3", this.form.uploadFiles[2]);
        postApiPurchasingSupplierSave(params).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("供应商添加成功");
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    //编辑供应商信息---------------------接口
    postApiPurchasingSupplierUpdateApi() {
      console.log(this.form.uploadFiles);
      return new Promise((resolve) => {
        let params = new FormData();
        params.append("id", this.form.id);
        params.append("name", this.form.name);
        params.append("supplyCode", this.form.supplyCode);
        params.append("contact", this.form.contact);
        params.append("mobile", this.form.mobile);
        params.append("address", this.form.address);
        params.append("email", this.form.email);
        params.append("startTime", this.form.startTime);
        params.append("stopTime", this.form.stopTime);
        params.append("materialClassValue", this.form.materialClassValue);
        params.append("file1", this.form.uploadFiles[0]);
        params.append("file2", this.form.uploadFiles[1]);
        params.append("file3", this.form.uploadFiles[2]);
        postApiPurchasingSupplierUpdate(params).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            // 如果有之前的图片先将之前的图片删除

            this.$Message.success("修改成功");
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    //供应种类接口------------------------------接口
    getProductCategoryListApi() {
      this.loading = true;
      this.materialClassTree = [];
      return new Promise((resolve) => {
        getProductCategoryList(this.data).then((res) => {
          if (res.code == 1) {
            this.materialClassTree = res.data;
            this.loading = false;
            this.form.materialClassValue.forEach((item) => {
              this.materialClassTree.forEach((it) => {
                if (it.id == item) {
                  it.isSupplyCheck = 0;
                }
              });
            });
            console.log("供应商种类", this.materialClassTree);
            resolve();
          }
        });
      });
    },
    //删除图片---------------------接口
    deleteApiCertificationPictureApi(url) {
      return new Promise((resolve) => {
        let params = {
          id: this.form.id,
          url: url,
        };
        deleteApiCertificationPicture(params).then((res) => {
          if (res.code == 1) {
            // this.$Message.success("删除成功");
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
.redDot {
  /deep/.ivu-form-item-label:before {
    content: "";
    margin-right: 0px;
  }
}
.selectItem {
  /deep/.ivu-select-input {
    height: 35px !important;
    line-height: 35px;
  }
}
.imgContent {
  width: 58px;
  height: 58px;
  display: flex;
  align-items: center;

  &-item {
    height: 100%;
    width: 58px;
    position: relative;
    text-align: center;
    line-height: 58px;
    display: inline-block;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    &-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
    }
  }
  &-item:hover &-item-cover {
    display: block;
  }
  &-item-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
}
</style>
